package com.common;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import com.common.db.DbPoolConnection;

public class PropertiesUtils {
	public static String proPath = "config_dev/db.properties";

	public static String getValue(String key) {
		Properties properties = new Properties();
		// 使用ClassLoader加载properties配置文件生成对应的输入流
		InputStream in = PropertiesUtils.class.getClassLoader().getResourceAsStream(proPath);
		// 使用properties对象加载输入流
		try {
			properties.load(in);
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return properties.getProperty(key);
	}

	public static void setValue(String key, String value) {
		Properties properties = new Properties();
		// 使用ClassLoader加载properties配置文件生成对应的输入流
		InputStream in = PropertiesUtils.class.getClassLoader().getResourceAsStream(proPath);
		// 使用properties对象加载输入流
		try {
			properties.load(in);
			in.close();
			FileOutputStream fos = new FileOutputStream(proPath);   
            // 将Properties集合保存到流中   
			properties.setProperty(key, value);
			properties.store(fos, "Copyright (c) Boxcode Studio");   
            fos.close();// 关闭流   

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Properties loadPropertyFile(String fullFile) {
		String webRootPath = null;
		if (null == fullFile || fullFile.equals(""))
			throw new IllegalArgumentException("Properties file path can not be null : " + fullFile);
		webRootPath = DbPoolConnection.class.getClassLoader().getResource("\\").getPath();
		webRootPath = new File(webRootPath).getParent();
		InputStream inputStream = DbPoolConnection.class.getClassLoader().getResourceAsStream(fullFile);
		;
		Properties p = null;
		try {
			// String profilepath = webRootPath + File.separator + fullFile;
			// System.out.println(profilepath);
			// inputStream = new FileInputStream(new File(profilepath));
			p = new Properties();
			p.load(inputStream);
		} catch (FileNotFoundException e) {
			throw new IllegalArgumentException("Properties file not found: " + fullFile);
		} catch (IOException e) {
			throw new IllegalArgumentException("Properties file can not be loading: " + fullFile);
		} finally {
			try {
				if (inputStream != null)
					inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return p;
	}
}
